package main

import (
	"log"
	"net/http"
	"os"
	"strings"
	"text/template"

	"github.com/PuerkitoBio/goquery"
)

// 获取HTML页面中需要的数据
func main() {
	if len(os.Args) < 2 {
		log.Fatal("请输入博客列表地址，格式如：./main.exe http://blog.sina.com.cn/s/articlelist_1704122375_0_1.html")
	}
	client := &http.Client{}
	req, err := http.NewRequest(http.MethodGet, os.Args[1], nil)
	if err != nil {
		log.Fatal(err)
	}
	res, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()
	if res.StatusCode != 200 {
		log.Fatalf("status code error: %d %s", res.StatusCode, res.Status)
	} else {
		log.Println("请求成功", res.StatusCode)
	}
	//转换数据为HTML对象模型
	doc, err := goquery.NewDocumentFromReader(res.Body)
	if err != nil {
		log.Fatal("NewDocumentFromReader:", err)
	}
	//查找元素
	doc.Find(".articleList .articleCell").Each(func(i int, s *goquery.Selection) {
		link, _ := s.Find("a").Attr("href")
		writeBlog(link)
	})
}

func writeBlog(link string) error {
	log.Println("博客链接：", link)
	res2, err := http.Get(link)
	defer res2.Body.Close()
	if err != nil {
		log.Fatal(err)
		return err
	}
	blog, err := goquery.NewDocumentFromReader(res2.Body)
	if err != nil {
		log.Fatal(err)
		return err
	}
	title := blog.Find("#articlebody .h1_tit").Text()
	content, err := blog.Find("#articlebody .BNE_cont").Html()
	time := blog.Find("#articlebody .time.SG_txtc").Text()
	tags := make([]string, 5)
	blog.Find("#articlebody .tagbox span").Each(func(i int, s *goquery.Selection) {
		tags = append(tags, s.Text())
	})

	time = strings.ReplaceAll(time, ":", "_")
	if title == "" {
		log.Println("老版UI")
		title = blog.Find("#articlebody .articalTitle .titName").Text()
		content, err = blog.Find("#articlebody .articalContent").Html()
	}
	if err != nil {
		log.Fatal("获取内容失败", err)
		return err
	}
	temp := template.Must(template.ParseFiles("./template.html"))
	data := make(map[string]string)
	data["title"] = title
	data["link"] = link
	data["content"] = content
	data["time"] = time
	data["tags"] = strings.Join(tags, " ")
	fileTitle := title + time
	f, err := os.Create("blog_list/" + fileTitle + ".html")
	if err != nil {
		log.Println(err)
		return err
	}
	err = temp.Execute(f, data)
	if err != nil {
		log.Fatal(err)
		f.Close()
		return err
	}
	log.Println(fileTitle, "written successfully")
	err = f.Close()
	if err != nil {
		log.Fatal(err)
		return err
	}
	return nil
}
